using System;
using System.Text.Json;

namespace DocumentCreationSystem.Models
{
    /// <summary>
    /// 文件命名配置模型
    /// </summary>
    public class FileNamingConfig
    {
        /// <summary>
        /// 章节文件命名模板
        /// </summary>
        public string ChapterNamingTemplate { get; set; } = "{BookTitle}_第{VolumeNumber:D2}卷_{VolumeName}_第{ChapterNumber:D3}章_{ChapterTitle}";

        /// <summary>
        /// 大纲文件命名模板
        /// </summary>
        public string OutlineNamingTemplate { get; set; } = "{BookTitle}_{OutlineType}_大纲";

        /// <summary>
        /// 角色设定文件命名模板
        /// </summary>
        public string CharacterNamingTemplate { get; set; } = "{BookTitle}_角色_{CharacterName}";

        /// <summary>
        /// 时间线文件命名模板
        /// </summary>
        public string TimelineNamingTemplate { get; set; } = "{BookTitle}_时间线_第{VolumeNumber:D2}卷";

        /// <summary>
        /// 世界设定文件命名模板
        /// </summary>
        public string WorldSettingNamingTemplate { get; set; } = "{BookTitle}_设定_{SettingType}";

        /// <summary>
        /// 是否自动清理文件名中的非法字符
        /// </summary>
        public bool AutoSanitizeFileNames { get; set; } = true;

        /// <summary>
        /// 是否使用中文数字格式
        /// </summary>
        public bool UseChineseNumbers { get; set; } = false;

        /// <summary>
        /// 默认文件扩展名
        /// </summary>
        public string DefaultFileExtension { get; set; } = ".txt";

        /// <summary>
        /// 是否在文件名中包含日期
        /// </summary>
        public bool IncludeDateInFileName { get; set; } = false;

        /// <summary>
        /// 日期格式
        /// </summary>
        public string DateFormat { get; set; } = "yyyy-MM-dd";

        /// <summary>
        /// 是否在文件名中包含时间
        /// </summary>
        public bool IncludeTimeInFileName { get; set; } = false;

        /// <summary>
        /// 时间格式
        /// </summary>
        public string TimeFormat { get; set; } = "HH-mm-ss";

        /// <summary>
        /// 文件名最大长度限制
        /// </summary>
        public int MaxFileNameLength { get; set; } = 200;

        /// <summary>
        /// 是否启用文件名去重
        /// </summary>
        public bool EnableFileNameDeduplication { get; set; } = true;

        /// <summary>
        /// 去重后缀格式
        /// </summary>
        public string DeduplicationSuffixFormat { get; set; } = "_{0:D2}";

        /// <summary>
        /// 配置创建时间
        /// </summary>
        public DateTime CreatedAt { get; set; } = DateTime.Now;

        /// <summary>
        /// 配置更新时间
        /// </summary>
        public DateTime UpdatedAt { get; set; } = DateTime.Now;

        /// <summary>
        /// 配置版本
        /// </summary>
        public string Version { get; set; } = "1.0";

        /// <summary>
        /// 配置名称
        /// </summary>
        public string Name { get; set; } = "默认配置";

        /// <summary>
        /// 配置描述
        /// </summary>
        public string Description { get; set; } = "系统默认的文件命名配置";

        /// <summary>
        /// 是否为默认配置
        /// </summary>
        public bool IsDefault { get; set; } = true;

        /// <summary>
        /// 验证配置的有效性
        /// </summary>
        public (bool IsValid, string ErrorMessage) Validate()
        {
            if (string.IsNullOrWhiteSpace(ChapterNamingTemplate))
                return (false, "章节命名模板不能为空");

            if (string.IsNullOrWhiteSpace(OutlineNamingTemplate))
                return (false, "大纲命名模板不能为空");

            if (string.IsNullOrWhiteSpace(CharacterNamingTemplate))
                return (false, "角色命名模板不能为空");

            if (string.IsNullOrWhiteSpace(TimelineNamingTemplate))
                return (false, "时间线命名模板不能为空");

            if (string.IsNullOrWhiteSpace(DefaultFileExtension))
                return (false, "默认文件扩展名不能为空");

            if (!DefaultFileExtension.StartsWith("."))
                return (false, "文件扩展名必须以点号开头");

            if (MaxFileNameLength < 50 || MaxFileNameLength > 500)
                return (false, "文件名最大长度必须在50-500之间");

            return (true, "");
        }

        /// <summary>
        /// 克隆配置
        /// </summary>
        public FileNamingConfig Clone()
        {
            var json = JsonSerializer.Serialize(this);
            return JsonSerializer.Deserialize<FileNamingConfig>(json) ?? new FileNamingConfig();
        }

        /// <summary>
        /// 序列化为JSON
        /// </summary>
        public string ToJson()
        {
            return JsonSerializer.Serialize(this, new JsonSerializerOptions 
            { 
                WriteIndented = true,
                Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            });
        }

        /// <summary>
        /// 从JSON反序列化
        /// </summary>
        public static FileNamingConfig? FromJson(string json)
        {
            try
            {
                return JsonSerializer.Deserialize<FileNamingConfig>(json);
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 重置为默认值
        /// </summary>
        public void ResetToDefault()
        {
            var defaultConfig = new FileNamingConfig();
            
            ChapterNamingTemplate = defaultConfig.ChapterNamingTemplate;
            OutlineNamingTemplate = defaultConfig.OutlineNamingTemplate;
            CharacterNamingTemplate = defaultConfig.CharacterNamingTemplate;
            TimelineNamingTemplate = defaultConfig.TimelineNamingTemplate;
            WorldSettingNamingTemplate = defaultConfig.WorldSettingNamingTemplate;
            AutoSanitizeFileNames = defaultConfig.AutoSanitizeFileNames;
            UseChineseNumbers = defaultConfig.UseChineseNumbers;
            DefaultFileExtension = defaultConfig.DefaultFileExtension;
            IncludeDateInFileName = defaultConfig.IncludeDateInFileName;
            DateFormat = defaultConfig.DateFormat;
            IncludeTimeInFileName = defaultConfig.IncludeTimeInFileName;
            TimeFormat = defaultConfig.TimeFormat;
            MaxFileNameLength = defaultConfig.MaxFileNameLength;
            EnableFileNameDeduplication = defaultConfig.EnableFileNameDeduplication;
            DeduplicationSuffixFormat = defaultConfig.DeduplicationSuffixFormat;
            
            UpdatedAt = DateTime.Now;
        }

        /// <summary>
        /// 获取中文数字
        /// </summary>
        public string GetChineseNumber(int number)
        {
            if (!UseChineseNumbers)
                return number.ToString();

            var chineseNumbers = new[] { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
            var chineseUnits = new[] { "", "十", "百", "千", "万" };

            if (number == 0) return chineseNumbers[0];
            if (number < 0) return "负" + GetChineseNumber(-number);

            var result = "";
            var unitIndex = 0;

            while (number > 0)
            {
                var digit = number % 10;
                if (digit != 0)
                {
                    result = chineseNumbers[digit] + (unitIndex > 0 ? chineseUnits[unitIndex] : "") + result;
                }
                else if (result.Length > 0 && !result.StartsWith(chineseNumbers[0]))
                {
                    result = chineseNumbers[0] + result;
                }

                number /= 10;
                unitIndex++;
            }

            // 处理特殊情况：十一 -> 一十一，但 十 -> 十
            if (result.StartsWith("一十") && result.Length > 2)
                result = result.Substring(1);

            return result;
        }
    }
}
